/**
 * Copyright (C)  2011  chen wei hua.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 2.0
 * or any later version published by the Free Software Foundation;
 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU Free Documentation License".
 */
package com.javaeye.delivery.service;

import java.util.Set;

import com.javaeye.delivery.dto.CustomerOrder;
import com.javaeye.delivery.dto.OrderDetail;
import com.javaeye.order.dto.PurchaseOrder;
import com.javaeye.order.dto.PurchaseOrderDetail;
import com.javaeye.common.util.DateUtils;

public class OrderInStoreService extends OrderService {
	
	public void saveOrder(CustomerOrder order) {
		//更新出货单为已经入库
		order.setStatus(ORDER_STATES_IN_STORE);
		order.setUpdateDate(DateUtils.now());
		getDao().saveOrder(order);
		
		String purchaseOrderId = order.getPurchaseOrderId();
		int productId;
		PurchaseOrderDetail purchaseOrderdetail;
		Set<OrderDetail> details = order.getOrderDetails();
		for (OrderDetail detail : details) {
			productId = detail.getProductId();
			//更新订单表里的已经入库数量
			purchaseOrderdetail = getPurchaseOrderDetailDao()
				.getPurchaseOrderDetail(purchaseOrderId, productId);
			purchaseOrderdetail.setInStoreNumber(purchaseOrderdetail.getInStoreNumber() + detail.getInStoreNumber());
			getPurchaseOrderDetailDao().savePurchaseOrderDetail(purchaseOrderdetail);
		}
		
		//如果全部入库完成更新订单表的状态
		PurchaseOrder purchaseOrder = getPurchaseOrderDao().getPurchaseOrderInfo(purchaseOrderId);
		Set<PurchaseOrderDetail> alldetails = purchaseOrder.getOrderDetails();
		if (isInstoreFinished(alldetails)) {
			purchaseOrder.setStatus(IOrderService.ORDER_STATES_IN_STORE);
			getPurchaseOrderDao().savePurchaseOrder(purchaseOrder);
		}
	}
	
	/**
	 * 是否全部入库完成
	 * @param details
	 * @return
	 */
	private boolean isInstoreFinished(Set<PurchaseOrderDetail> details) {
		int allCount = details.size();
		int finishCount = 0;
		for (PurchaseOrderDetail detail : details) {
			if (detail.getInStoreNumber() == detail.getNumber()) {
				finishCount++;
			}
		}
		return finishCount == allCount;
	}

}
